/*
 * @lc app=leetcode.cn id=331 lang=javascript
 *
 * [331] 验证二叉树的前序序列化
 */

// @lc code=start
/**
 * @param {string} preorder
 * @return {boolean}
 */
/**
 *  将叶子节点替换为 # 
 *    1. 如果遇到两个 # 则说明前一个节点为叶子节点
 *    2. 删除两个 #， 并将叶子节点替换为 #
 */
var isValidSerialization = function (preorder) {
  let preOrder = preorder.split(',');
  let stack = [];
  for (let i = 0; i < preOrder.length; i++) {
    let val = preOrder[i];
    stack.push(val);
    while (stack[stack.length - 1] === '#' && stack[stack.length - 2] === '#') {
      stack.pop();
      stack.pop();
      stack[stack.length - 1] = '#';
    }
  }
  return stack.length === 1 && stack[0] === '#';
}
// @lc code=end

